package com.hxd.otc.module.login.activity;

import android.content.Intent;

import com.alibaba.verificationsdk.ui.VerifyType;
import com.hxd.otc.MainActivity;
import com.hxd.otc.R;
import com.hxd.otc.base.BaseActivity;
import com.hxd.otc.base.BaseFragment;
import com.hxd.otc.common.RecentLoginAccountInfoHelper;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.module.login.bean.AccountBean;
import com.hxd.otc.module.login.contract.LoginContract;
import com.hxd.otc.module.login.fragment.FingerprintLoginFragment;
import com.hxd.otc.module.login.fragment.NorLoginFragment;
import com.hxd.otc.module.login.presenter.LoginPresenter;
import com.hxd.otc.module.my.bean.AppInfoBean;
import com.hxd.otc.module.wallet.activity.RemotePayActivity;
import com.hxd.otc.utils.LogUtils;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.utils.VerifyTypeUtils;
import com.hxd.otc.utils.download.DownloadManagerUtil;
import com.wei.android.lib.fingerprintidentify.FingerprintIdentify;

/**
 * 作  者 :  胡庆岭
 * 时  间 :  2018/6/4 10:21
 * 描  述 :  ${登录Activity}
 */
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View {

    //是否是远程调启钱包支付
    private boolean isRemotePay = false;
    private AppInfoBean mUpdateVersionInfo;
    public static final String EXTRA_FINISH_SKIP_MAIN = "finish_skip_main";
    private boolean mIsFinishSkipMain;//是否在结束登录页面时跳转至主界面，当一些二级界面主动跳转登录界面返回时不想回到主界面时可以传false

    public static final int REQUEST_CODE_FORGET_PASSWORD = 2001;
    private FingerprintIdentify mFingerprintIdentify;

    public enum LoginMethod {
        NOR, FINGERPRINT
    }

    private LoginMethod mLoginMethod = LoginMethod.NOR;
    private BaseFragment mCurFragment;

    @Override
    protected int getLayoutId() {
        return R.layout.layout_container;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        isRemotePay = intent.getBooleanExtra(RemotePayActivity.REMOTE_COME, false);
        mIsFinishSkipMain = intent.getBooleanExtra(EXTRA_FINISH_SKIP_MAIN, true);

        //判断用户是否开启了指纹登录
        boolean fingerprintStatus = RecentLoginAccountInfoHelper.isFingerprintStatus();

        if (fingerprintStatus) {
            mFingerprintIdentify = new FingerprintIdentify(getApplicationContext());
            mFingerprintIdentify.setSupportAndroidL(true);
            mFingerprintIdentify.init();

            //表示用户注销了指纹，则将指纹给关闭
            if (mFingerprintIdentify.isRegisteredFingerprint()) {
                mLoginMethod = LoginMethod.FINGERPRINT;
            }
        }
        onSwitchLoginMode(mLoginMethod);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void initEvent() {
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter(this);
    }

    public void clickForgetPassword() {
        $startActivityForResult(ForgetPasswordActivity.class, REQUEST_CODE_FORGET_PASSWORD);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_FORGET_PASSWORD && resultCode == RESULT_OK) {
            sessionId = null;
        }
    }

    public void clickRegister() {
        $startActivity(RegisterActivity.class, false);
    }

    /**
     * @param account   账号
     * @param password  密码
     * @param encrypted 密码是否已加密
     */
    public void login(String account, String password, boolean encrypted) {
        if (!account.equals(lastAccount)) {
            sessionId = null;
        }

        updateLoginBtnClickEnable(false);
        lastAccount = account;
        showSpinnerDlg(getString(R.string.be_logging_in), false);
        mPresenter.login(account, password, sessionId, encrypted);
    }

    private void updateLoginBtnClickEnable(boolean enable) {

        if (mCurFragment == null) return;

        if (mCurFragment instanceof NorLoginFragment) {
            ((NorLoginFragment) mCurFragment).setClickEnable(enable);
        } else if (mCurFragment instanceof FingerprintLoginFragment) {
            ((FingerprintLoginFragment) mCurFragment).setClickEnable(enable);
        }

    }

    @Override
    public void loginSucceed(AccountBean bean) {
        dismissSpinnerDlg();
        updateLoginBtnClickEnable(true);
        UserHelper.putLoginResult(bean);
        if (isRemotePay) {
            //如果是远程支付登录，不返回到主页面
            setResult(RemotePayActivity.LOGIN_SUCCESS);
        } else if (mIsFinishSkipMain) {
            $startActivity(MainActivity.class);
        }
        finish();
    }

    VerifyTypeUtils verifyTypeUtils;
    String sessionId;
    String lastAccount;

    @Override
    public void verifyTypeVerification() {
        showToast("用户名或密码输入错误超过3次，请进行安全验证！");

        verifyTypeUtils = new VerifyTypeUtils();
        verifyTypeUtils.callSDKDoVerification(VerifyType.NOCAPTCHA, null, this, new VerifyTypeUtils.VerifyTypeCallBack() {
            @Override
            public void onSucced(String sessionID) {
                LogUtils.e("======onSucced============" + sessionID);
                showToast(getString(R.string.ver_succed));
                sessionId = sessionID;
            }
        });
    }

    @Override
    public void getUpdateVersionInfoSuccess(AppInfoBean appInfoBean) {
        mUpdateVersionInfo = appInfoBean;
        doNewVersionUpdate();
    }

    @Override
    public void onLoginFail(int errType, String errMessage) {
        dismissSpinnerDlg();
        switch (errType) {
            case 10001001://需要滑块验证
                verifyTypeVerification();
                break;
            case 10001000:
            case 10004007:
                showToast(ResourceUtil.getString(R.string.incorrect_user_name_or_password));
                break;
            default:
                if ("Invalid Credentials".equals(errMessage)) {
                    showToast(ResourceUtil.getString(R.string.incorrect_user_name_or_password));
                } else {
                    showToast(errMessage);
                }
                break;
        }
        updateLoginBtnClickEnable(true);
    }

    private void doNewVersionUpdate() {
        if (DownloadManagerUtil.hasNewVersion(mUpdateVersionInfo, false)) {
            DownloadManagerUtil.showUpdateVersionDialog(this, mUpdateVersionInfo);
        }
    }

    @Override
    public void onBackPressed() {
        if (isRemotePay) {
            setResult(RemotePayActivity.LOGIN_FAIL);
        } else if (mIsFinishSkipMain) {
            $startActivity(MainActivity.class);
        }
        finish();
    }

    public void onSwitchLoginMode(LoginMethod loginMethod) {
        mLoginMethod = loginMethod;

        if (LoginMethod.FINGERPRINT.equals(loginMethod)) {
            mCurFragment = new FingerprintLoginFragment();
        } else {
            mCurFragment = new NorLoginFragment();
        }
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fl_container, mCurFragment)
                .commit();
    }
}
